package org.example.advice;

import org.example.constant.BaseErrorCode;
import org.example.exception.BaseException;
import org.example.vo.GenericResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class BaseErrorHandler {
    @Autowired
    private MessageSource messageSource;
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GenericResponse methodNotSupport() {
        Integer code = BaseErrorCode.BAD_REQUEST.code;
        String errMsg = messageSource.getMessage(BaseErrorCode.BAD_REQUEST.message, null, Locale.CHINA);
        GenericResponse gr = GenericResponse.builder()
                .code(code)
                .message(errMsg)
                .data(Collections.emptyMap())
                .build();

        return gr;
    }

    /**
     * 404错误处理
     *
     * @return ResponseEntity
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public GenericResponse notFound() {
        Integer code = BaseErrorCode.NOT_FOUND.code;
        String errMsg = messageSource.getMessage(BaseErrorCode.NOT_FOUND.message, null, Locale.CHINA);
        GenericResponse gr = GenericResponse.builder()
                .code(code)
                .message(errMsg)
                .data(Collections.emptyMap())
                .build();

        return gr;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GenericResponse argumentNotValid(MethodArgumentNotValidException e) {
        List<ObjectError> allErrs = e.getBindingResult().getAllErrors();
        String data = allErrs.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("; "));
        Integer code = BaseErrorCode.BAD_REQUEST.code;
        String errMsg = messageSource.getMessage(BaseErrorCode.BAD_REQUEST.message, null, Locale.CHINA);
        GenericResponse gr = GenericResponse.builder()
                .code(code)
                .message(errMsg)
                .data(data)
                .build();

        return gr;
    }

    /**
     * 未知异常处理
     *
     * @param e 未知异常
     * @return ResponseEntity
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public GenericResponse unknownError(BaseException e) {
        Integer code = BaseErrorCode.INVOKE_FAIL.code;
        String errMsg = messageSource.getMessage(BaseErrorCode.INVOKE_FAIL.message, null, Locale.CHINA);
        GenericResponse gr = GenericResponse.builder()
                .code(code)
                .message(errMsg)
                .data(Collections.emptyMap())
                .build();

        return gr;
    }

    /**
     * 未知异常处理
     *
     * @param e 未知异常
     * @return ResponseEntity
     */
    @ExceptionHandler(value = Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public GenericResponse unknownError(Throwable e) {
        // 以防万一有些人编码太烂，没有异常处理的概念，尝试在这统一拦截
        log.error("caught internal error=[{}]", e.getMessage(), e);
        Integer code = BaseErrorCode.INTERNAL_ERROR.code;
        String errMsg = messageSource.getMessage(BaseErrorCode.INTERNAL_ERROR.message, null, Locale.CHINA);
        GenericResponse gr = GenericResponse.builder()
                .code(code)
                .message(errMsg)
                .data(Collections.emptyMap())
                .build();

        return gr;
    }
}
